<template>
  <!-- 品牌管理 -->
  <div>
    <el-button type="primary" @click="showDialog" icon="el-icon-plus" size="small" style="margin: 0 0 10px 0;">添加</el-button>
    <template>
    <el-table :data="list" style="width: 100%" border>
      <el-table-column type="index" label="序号" width="100px"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template slot-scope="scope">
          <img :src="scope.row.logoUrl" alt="" style="width: 100px; height: 60px;">
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" icon="el-icon-edit" @click="updateTradeMark(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteTradeMark(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </template>
  <!-- 分页区域 -->
  <el-pagination
      style="margin-top: 20px; text-align: center;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 5,10]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->,sizes,total"
      :total="total">
    </el-pagination>
    <!-- 添加的对话框 -->
    <el-dialog
      :title="tmForm.id?'修改品牌':'添加品牌'"
      :visible.sync="dialogVisible"
      width="50%">
      <el-form style="width: 80%;" :model="tmForm" :rules="rules" ref="tmFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!--这里收集数据：不能使用v-model，因为不是表单元素
            action:设置图片上传的地址
            :on-success:可以检测到图片上传成功，当图片上传成功，会执行一次
            :before-upload：可以在上传图片之前，会执行一次
          -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  
</template>

<script>
// import {getTrademark} from '@/api/product/tradeMark'
export default {
    name:'tradeMark',
    data() {
      // 自定义校验规则
      var validateTmName = (rule, value, callback) => {
        if(value.length<2||value.length>10){
          callback(new Error('品牌名称2-10位'))
        }else{
          callback()
        }
      };
      return {
        page:1,
        limit:3,
        total:0,
        // 列表展示的数据
        list:[],
        dialogVisible:false,
        // 收集品牌信息
        tmForm:{
          tmName:'',
          logoUrl: ''
        },
        rules: {
          tmName: [
            { required: true, message: '请输入品牌名称', trigger: 'blur' },
            // { min: 2, max: 10, message: '品牌名称2-10位', trigger: 'change' }
            { validator: validateTmName, trigger: 'change' }
          ],
          logoUrl: [
            { required: true, message: '请选择品牌的图片'},
          ],
        }
      }
    },
    mounted(){
      this.getPageList()
      // console.log(this.$API);
    },
    methods:{
      // 获取品牌列表的数据
      getPageList(){
        // 获取品牌列表的接口
          this.$API.trademark.reqTradeMarkList(this.page,this.limit).then(res=>{
          console.log(res);
          if(res.code == 200){
            this.total =res.data.total
            this.list = res.data.records
          }
        })
      },
      handleSizeChange(newLimit) {
        // console.log(`每页 ${val} 条`);
        this.limit = newLimit
        this.getPageList()
      },
      handleCurrentChange(newPage) {
        // console.log(`当前页: ${val}`);
        this.page = newPage
        this.getPageList()
      }, 
      // 点击添加按钮
      showDialog(){
        this.dialogVisible = true
        //清除数据，此处正好清除id，添加时不带id
        this.tmForm = { tmName: "", logoUrl: "" };
      },
      // 点击修改按钮
      updateTradeMark(row){
        this.dialogVisible = true
        // 要拷贝这个数据，不要直接用，此处row为浅拷贝，修改时有id
        this.tmForm = {...row}
      },
      // 点击确定 添加或修改品牌
      addOrUpdateTradeMark(){
        this.$refs.tmFormRef.validate((valid) => {
          if(valid){
              this.$API.trademark.reqAddOrUpdateTradeMark(this.tmForm).then(res=>{
                if(res.code == 200){
                  this.$message({type: 'success',message:this.tmForm.id?'修改品牌成功':'添加品牌成功'})
                }
                this.dialogVisible = false
                this.getPageList()
              })
            }
        }) 
      },
      // 上传图片成功
      handleAvatarSuccess(res, file) {
        //res：上传成功之后返回前端数据
        //file:上传成功之后服务器返回前端数据
        //收集品牌图片数据，因为将来需要带给服务器
        this.tmForm.logoUrl = res.data;
      },
      // 图片上传之前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      // 删除功能
      deleteTradeMark(id){
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$API.trademark.reqDeleteTradeMark(id).then(res=>{
            if(res.code == 200){
              this.$message({type: 'success',message: '删除成功!'});
              this.getPageList()
            }else{this.$message.error('删除失败')}
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        
      }
      
    }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>